#
# scorebar.py
#
# implementation of the score bar.
#

import pygame
import data

import constants as c

font = None
def rendertxt(txt):
    global font
    try:
        return font.render(txt, 1, (255, 255, 255))
    except AttributeError:
        font = pygame.font.Font(None, 26)
        return rendertxt(txt)

class Scorebar(pygame.sprite.Sprite):
    def __init__(self):
        pygame.sprite.Sprite.__init__(self)

        # store an original copy of the background.
        self.orig, self.rect = data.load_image('topbar.png', None)
        self.image = self.orig.copy()

        self.rect.topleft = (0, 0)

        self._stats = { 'dead birds': '0',
                'saved birds': '0',
                'time elapsed': '0',
                'kWh generated': '0'}

        # the order in which to show the updates.
        self._nowshow = ['dead birds', 'saved birds',
                            'time elapsed', 'kWh generated']
        self._frames = 0
        self._dirty = 0

    def _clear(self):
        'clear the display. and set the dirty flag.'
        self.image = self.orig.copy()
        self._dirty = 1

    def _fps(self, txt):
        'write some fps to the display. a debug function. also broken'
        self._clear()

        # write the text.
        txt = rendertxt(txt)
        self.image.blit(txt, txt.get_rect(topleft=(10, 10)))
        self.update({}) # this breaks the fps function. i have no desire to fix

    def update(self, kwargs):
        '''update the round robin of text with game stats.
        clears the dirty flag.'''

        self._clear()
        x = 30
        for kw, txt in kwargs.items():
            if kw in self._stats:
                ts = rendertxt('%s = %s' % (kw, txt))
                self.image.blit(ts, ts.get_rect(topleft=(x , 10)))
                # dirty method to ensure that x does not vary too much frame
                # to frame.
                x += (ts.get_width() + 50) / 20 * 20




